#!/bin/bash
# REQUEST_FOR_LOG_TYPE_ARRAY=("Notification" "Pgyer")
# sh ${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/brances_info_log.sh -envInfoF "${Package_Environment_FILE_PATH}" --request-for-log-types "${REQUEST_FOR_LOG_TYPE_ARRAY[*]}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" -resultSaveToJsonF "${TEST_DATA_RESULT_FILE_PATH}"
JQ_EXEC=`which jq`


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

function logSuccessMsg() {
    printf "${GREEN}$1${GREEN}\n${NC}"
}

function logMsg() {
    printf "$1\n${NC}"
}

function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}


# shell 参数具名化
show_usage="args: [-envInfoF, -requestFors, -comScriptHomeDir, -resultSaveToJsonF]\
                                  [---environment-json-file=, -request-for-log-types=, --common-script-home-dir=, --result-save-to-json-file-path=]"

while [ -n "$1" ]
do
        case "$1" in
                -envInfoF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;; # 环境文件
                -requestFors|--request-for-log-types) REQUEST_FOR_LOG_TYPE_ARRAY_STRING=$2; shift 2;;   # 要请求哪些类型 ("Notification" "Pgyer")
                -comScriptHomeDir|--common-script-home-dir) COMMON_SCRIPT_HOME_DIR_Absolute=$2; shift 2;;   # 公共目录，为了同时能够等于引入①为了计算提交测试了多久;②为了引用markdown的脚本
                -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done
# 参数1：
if [ ! -f "${Environment_FILE_PATH}" ]; then
    echo "❌:您的环境文件Environment_FILE_PATH=${Environment_FILE_PATH}未设置或不存在，请先设置"
    exit_script
fi

# 参数2：
# REQUEST_FOR_LOG_TYPE_ARRAY_STRING

# 参数3：
bulidScriptCommon_dir_Absolute=${COMMON_SCRIPT_HOME_DIR_Absolute}
if [ -z "${bulidScriptCommon_dir_Absolute}" ] || [ ! -d "${bulidScriptCommon_dir_Absolute}" ];then
    echo "❌Error:获取分支时候,您的【${bulidScriptCommon_dir_Absolute}】文件夹不存在，请检查是否source的时候漏传参了！"
    exit_script
fi
branchs_info_log_common_file_Absolute="${bulidScriptCommon_dir_Absolute}/brances_info/brances_info_log/brances_info_log_common.sh"
commonDateFunctionFilePath="${bulidScriptCommon_dir_Absolute}/date/function_date.sh"

qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_json_file_check_script_path="$(sh ${qscript_path_get_filepath} qbase json_file_check)"

#TEST_DATA_RESULT_FILE_PATH="${bulidScriptCommon_dir_Absolute}/brances_info/brances_info_log/test/data/test_data_save_result.json"
#if [ ! -f "${TEST_DATA_RESULT_FILE_PATH}" ]; then
#    echo "要用来保存信息值的测试文件${TEST_DATA_RESULT_FILE_PATH}不存在，去检查❌"
#else
#    RESULT_SALE_TO_JSON_FILE_PATH=${TEST_DATA_RESULT_FILE_PATH}
#fi

markdownFun_script_file_Absolute="${bulidScriptCommon_dir_Absolute}/markdown/function_markdown.sh"
source "${markdownFun_script_file_Absolute}" # 为了使用 markdown_fontColor 等 markdown 方法

# 参数4
if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
    echo "❌:您通过 -resultSaveToJsonF 传入的要存放分支信息文件路径RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH}还未设置或者不存在，请检查！"
    exit_script
fi

# 获取当前包所含的功能分支信息
function getCurrentBranchLog() {
    while [ -n "$1" ]
    do
        case "$1" in
            -devBranchsJsonF|--devBranchs-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
#            -ignoreBranchNames|--ignoreBranchNameArray) ignoreBranchNameArray=$2; shift 2;;
            -branchLogFor|--branchLogFor) branchLogFor=$2; shift 2;;  # Notification / Pgyer
            -envJsonF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;;
            -shouldMD|--should-markdown) shouldMarkdownCurrent=$2; shift 2;;
            -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
            --) break ;;
            *) echo $1,$2; break ;;
        esac
    done

    if [ ! -f "${Develop_Branchs_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您之前保存本次打包的当前所含的分支信息的Develop_Branchs_FILE_PATH=${Develop_Branchs_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi
    
    if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您即将用来保存本次打包的当前分支信息结果的文件RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi

    
    PackageNetworkType=$(cat $Environment_FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')
    
    if [ "${branchLogFor}" == "Notification" ]; then
        echo "💡 正获取显示在到【企业微信】上的【本次打包】信息"
        showBranchLogFlag='true'
        showBranchName='true'
        showBranchTimeLog='all'
        showBranchAtLog='true'
        showBranchTable='false' # 通知也暂时都不显示
        showCategoryName='true' # 通知时候显示
    elif [ "${branchLogFor}" == "Pgyer" ]; then
        echo "💡 正获取显示在到【蒲公英】上的【本次打包】信息"
        if [ "${PackageNetworkType}" == "product" ]; then
            showBranchLogFlag='false'
            showBranchName='false'
            showBranchTimeLog='none'
            showBranchAtLog='false'
            showBranchTable='false'
            showCategoryName='false' # 更新信息上，如果是生产环境，分支类别暂不显示，其他环境显示
        else
            showBranchLogFlag='true'    # 对更新信息的显示,flag只有在"非生产"环境下才显示
            showBranchName='false'
            showBranchTimeLog='none'
            showBranchAtLog='true'
            showBranchTable='false'
            showCategoryName='true' # 更新信息上，如果是生产环境，分支类别暂不显示，其他环境显示
        fi
    else
        echo "❌Error: $FUNCNAME 获取当前分支信息的日志类型入参错误:${branchLogFor}，请检查"
        exit 1
    fi
    
    currentBranchLogStringResult=""
    Escape_CURRENT_ARRAY_STRING=""

    currentHeaderString="当前包新增功能分支信息如下(相比线上包,而不是上个打出的包)："
    currentBranchLogStringResult+="${currentHeaderString}"
    Escape_CURRENT_ARRAY_STRING+="\"${currentHeaderString}\""

    buildContainBranchMaps=$(cat ${Develop_Branchs_FILE_PATH} | ${JQ_EXEC} -r '.package_merger_branchs') # -r 去除字符串引号
    
    RESULT_FULL_CURRENT_STRING_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.full"
    if [ -z "${buildContainBranchMaps}" ] || [ "${buildContainBranchMaps}" == "null" ]; then
        echo "⚠️友情提示：您的${Develop_Branchs_FILE_PATH}文件中不存在已合如的package_merger_branchs数据"
        EMPTY_FULL_CURRENT_STRING="warning: no any current branchs info"
        currentBranchLogStringResult+=${EMPTY_FULL_CURRENT_STRING}
        Escape_CURRENT_ARRAY_STRING+=",\"${EMPTY_FULL_CURRENT_STRING}\""
        updateBranchResultFileKeyValue "${RESULT_SALE_TO_JSON_FILE_PATH}" "${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}" "${EMPTY_FULL_CURRENT_STRING}"
    else
        debug_log "正在引入方法文件(为了使用 getAllBranchLogString)：source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir \"${bulidScriptCommon_dir_Absolute}\" --branch-info-json-file \"${Develop_Branchs_FILE_PATH}\""
        source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir "${bulidScriptCommon_dir_Absolute}" --branch-info-json-file "${Develop_Branchs_FILE_PATH}"
        
        RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.branch"
        RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY="branch_info_result.${branchLogFor}.current.category"
        debug_log "正在使用引入文件 ${BLUE}${branchs_info_log_common_file_Absolute} ${NC}中的方法(获取当前打包信息):《 ${BLUE}getAllBranchLogString -branchMaps \"${buildContainBranchMaps}\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -commonDateFunctionFilePath \"${commonDateFunctionFilePath}\" -shouldMD \"${shouldMarkdownCurrent}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}\" ${NC}》${NC}"
        getAllBranchLogString -branchMaps "${buildContainBranchMaps}" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -commonDateFunctionFilePath "${commonDateFunctionFilePath}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_CURRENT_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_CURRENT_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_CURRENT_STRING_SALE_BY_KEY}"
        currentBranchLogStringResult+="\n${LAST_BRANCHS_INFO_STRING}"

        Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote=${Escape_LAST_BRANCH_ARRAY_ONLY_STRING: 1:${#Escape_LAST_BRANCH_ARRAY_ONLY_STRING}-2} # 去掉前后的双引号，再去做数据的更改
        Escape_CURRENT_ARRAY_STRING+=",\"${Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote}\""
    fi

    # 去除最后一个字符,即逗号"," (当开头一定有值的时候，我们在加字符串的时候，可以选择在前面加逗号，这样就不用在尾部去除了。但是一定得开头有值)
    # if [ -n "${Escape_CURRENT_ARRAY_STRING}" ] && [ "${Escape_CURRENT_ARRAY_STRING}" != "[" ]; then
    #     Escape_CURRENT_ARRAY_STRING=${Escape_CURRENT_ARRAY_STRING: 0:${#Escape_CURRENT_ARRAY_STRING}-2}
    # fi
    
#    echo "============当前打包信息currentBranchLogStringResult(${branchLogFor})============\n${currentBranchLogStringResult}"
}



# 获取上个线上版本的上线及所含功能分支的信息
function getLastOnlineVersionLog() {
    while [ -n "$1" ]
    do
        case "$1" in
            -historyVersionJsonF|--history-version-json-file) History_Versions_FILE_PATH=$2; shift 2;;
            -branchLogFor|--branchLogFor) branchLogFor=$2; shift 2;;
            -envJsonF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;;
            # -shouldMD|--should-markdown) shouldMarkdownLastOnline=$2; shift 2;;
            -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
            --) break ;;
            *) echo $1,$2; break ;;
        esac
    done

    if [ ! -f "${History_Versions_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您之前保存本次打包前的历史版本信息分支的History_Versions_FILE_PATH=${History_Versions_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi
    
    if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您即将用来保存本次打包的当前分支信息结果的文件RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi
    
    PackageNetworkType=$(cat $Environment_FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')
    
    if [ "${branchLogFor}" == "Notification" ]; then
        echo "💡 正获取显示在到【企业微信】上的【上次打包】信息"
        showBranchLogFlag='false'
        showBranchName='false'
        showBranchTimeLog='only_last'
        showBranchAtLog='false'
        showBranchTable='false'
        showCategoryName='false' # 已上线的，分支类型都不显示
    elif [ "${branchLogFor}" == "Pgyer" ]; then
        echo "💡 正获取显示在到【蒲公英】上的【上次打包】信息"
        if [ "${PackageNetworkType}" == "product" ]; then
            showBranchLogFlag='false'
            showBranchName='false'
            showBranchTimeLog='none'
            showBranchAtLog='false'
            showBranchTable='false'
            showCategoryName='false' # 已上线的，分支类型都不显示
        else
            showBranchLogFlag='false'
            showBranchName='false'
            showBranchTimeLog='only_last'
            showBranchAtLog='false'
            showBranchTable='false'
            showCategoryName='false' # 已上线的，分支类型都不显示
        fi
    else
        echo "$FUNCNAME ❌获取上个线上版本的上线及所含功能分支的信息的日志类型入参错误:branchLogFor=${branchLogFor}，请检查"
        exit 1
    fi
    
    lastOnlineVersionLogStringResult=""
    Escape_LASTONLINE_ARRAY_STRING=''

    lastOnlineHeaderString="上个线上版本分支信息："
    lastOnlineVersionLogStringResult+="${lastOnlineHeaderString}"

    # fileValue_origin_withDoubleQuote=${Escape_LAST_BRANCH_ARRAY_STRING}
    # #echo "======fileValue_origin_withDoubleQuote=${fileValue_origin_withDoubleQuote}"
    # echo "======fileValue_origin_withDoubleQuote_echo=${fileValue_origin_withDoubleQuote//\\n/\\\\n}" # 这里转义换行符只是为了 echo 显示而已，没其他用处
    # fileValue_origin_noDoubleQuote=${fileValue_origin_withDoubleQuote: 1:${#fileValue_origin_withDoubleQuote}-2}
    # #echo "======fileValue_origin_noDoubleQuote=${fileValue_origin_noDoubleQuote}"
    # echo "======fileValue_origin_noDoubleQuote_echo=${fileValue_origin_noDoubleQuote//\\n/\\\\n}" # 这里转义换行符只是为了 echo 显示而已，没其他用处
    # Escape_LAST_BRANCH_ARRAY_STRING=${fileValue_origin_noDoubleQuote}

    Escape_LASTONLINE_ARRAY_STRING+="\"${lastOnlineHeaderString}\","


    RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.full"
    if [ ! -f "${History_Versions_FILE_PATH}" ];then
        EMPTY_FULL_LASTONLINE_STRING="warning: no any history branchs info"
        lastOnlineVersionLogStringResult+="${EMPTY_FULL_LASTONLINE_STRING}"
        Escape_LASTONLINE_ARRAY_STRING+="\"${EMPTY_FULL_LASTONLINE_STRING}\","
        updateBranchResultFileKeyValue "${RESULT_SALE_TO_JSON_FILE_PATH}" "${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}" "${EMPTY_FULL_LASTONLINE_STRING}"
    else
        lastOnlineVersionMapString=$(cat ${History_Versions_FILE_PATH} | ${JQ_EXEC} -r '.history_versions[0]' ) # -r 去除字符串引号
        lastOnlineVersionTimeString=$(echo ${lastOnlineVersionMapString} | ${JQ_EXEC} -r '.online_time') # -r 去除字符串引号

        RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.branch"
        RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY="branch_info_result.${branchLogFor}.lastOnline.category"
        debug_log "正在执行命令(获取上次版本信息):《 getBranchsLogFromMapAndKey -branchRootMap \"${lastOnlineVersionMapString}\" -branchsKey \"online_brances\" -showCategoryName \"${showCategoryName}\" -showFlag \"${showBranchLogFlag}\" -showName \"${showBranchName}\" -showTime \"${showBranchTimeLog}\" -showAt \"${showBranchAtLog}\" -showTable \"${showBranchTable}\" -shouldMD \"${shouldMarkdownLastOnline}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -resultBranchKey \"${RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY}\" -resultCategoryKey \"${RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY}\" -resultFullKey \"${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}\" 》"
        getBranchsLogFromMapAndKey -branchRootMap "${lastOnlineVersionMapString}" -branchsKey "online_brances" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -shouldMD "${shouldMarkdownLastOnline}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_LASTONLINE_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_LASTONLINE_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_LASTONLINE_STRING_SALE_BY_KEY}"
        lastOnlineVersionLogStringResult+="\n${LAST_BRANCHS_INFO_STRING}"


        Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote=${Escape_LAST_BRANCH_ARRAY_ONLY_STRING: 1:${#Escape_LAST_BRANCH_ARRAY_ONLY_STRING}-2} # 去掉前后的双引号，再去做数据的更改
        Escape_LASTONLINE_ARRAY_STRING+="\"${Escape_LAST_BRANCH_ARRAY_ONLY_STRING_noDoubleQuote}\","
    fi

    # 去除最后一个字符,即逗号","
    if [ -n "${Escape_LASTONLINE_ARRAY_STRING}" ]; then
        Escape_LASTONLINE_ARRAY_STRING=${Escape_LASTONLINE_ARRAY_STRING: 0:${#Escape_LASTONLINE_ARRAY_STRING}-1}
    fi


#    echo "============上个线上版本分支信息lastOnlineVersionLogStringResult============\n${lastOnlineVersionLogStringResult}"
}

# 获取Map指定key值的branch数组信息
function getBranchsLogFromMapAndKey() {
    while [ -n "$1" ]
    do
            case "$1" in
                    -branchRootMap|--branchRootMap) branchRootMap=$2; shift 2;;
                    -branchsKey|--branchsKey) branchsKey=$2; shift 2;;
                    -showCategoryName|--show-category-name) showCategoryName=$2; shift 2;;
                    -showFlag|--show-branchLog-Flag) showBranchLogFlag=$2; shift 2;;
                    -showName|--show-branchName) showBranchName=$2; shift 2;;
                    -showTime|--show-branchTimeLog) showBranchTimeLog=$2; shift 2;;
                    -showAt|--show-branchAtLog) showBranchAtLog=$2; shift 2;;
                    -showTable|--show-branchTable) showBranchTable=$2; shift 2;;
                    -shouldMD|--should-markdown) shouldMarkdown=$2; shift 2;;
                    -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
                    -resultBranchKey|--result-branch-array-save-by-key) RESULT_BRANCH_ARRAY_SALE_BY_KEY=$2; shift 2;;   # 分支branch元素数组结果,用什么key保存到上述文件
                    -resultCategoryKey|--result-category-array-save-by-key) RESULT_CATEGORY_ARRAY_SALE_BY_KEY=$2; shift 2;;   # 分类category元素数组结果,用什么key保存到上述文件
                    -resultFullKey|--result-full-string-save-by-key) RESULT_FULL_STRING_SALE_BY_KEY=$2; shift 2;;   # 总字符串结果,用什么key保存到上述文件
                    --) break ;;
                    *) echo $1,$2; break ;;
            esac
    done
    
    #echo "branchsKey=${branchsKey}"
    
    #branchMapArray=$(echo ${branchRootMap} | ${JQ_EXEC} -r '.online_brances') # -r 去除字符串引号
    # [如何在shell中使用jq cmd变量](https://www.5axxw.com/questions/content/5ucfc4)
    branchMapArray=$(echo ${branchRootMap} | jq -r --arg branchsKey "$branchsKey" '.[$branchsKey]')
    #echo ">>>>>>>>>>>>>>>>branchMapArray=${branchMapArray}"
    
    debug_log "正在引入方法文件(为了使用 getAllBranchLogString)：source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir \"${bulidScriptCommon_dir_Absolute}\" --branch-info-json-file \"${Develop_Branchs_FILE_PATH}\""
    source ${branchs_info_log_common_file_Absolute} -commonFunHomeDir "${bulidScriptCommon_dir_Absolute}" --branch-info-json-file "${Develop_Branchs_FILE_PATH}"
    getAllBranchLogString -branchMaps "${branchMapArray}" -showCategoryName "${showCategoryName}" -showFlag "${showBranchLogFlag}" -showName "${showBranchName}" -showTime "${showBranchTimeLog}" -showAt "${showBranchAtLog}" -showTable "${showBranchTable}" -commonDateFunctionFilePath "${commonDateFunctionFilePath}" -shouldMD "${shouldMarkdown}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -resultBranchKey "${RESULT_BRANCH_ARRAY_SALE_BY_KEY}" -resultCategoryKey "${RESULT_CATEGORY_ARRAY_SALE_BY_KEY}" -resultFullKey "${RESULT_FULL_STRING_SALE_BY_KEY}"
}


# 初始化最后的分支信息，并保存到环境文件中指定的那个保存文件里，方便后续直接从文件中获取
function initLastAllChangeLog() {
    while [ -n "$1" ]
    do
        case "$1" in
            -envInfoF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;;
            # -developBranchsJsonF|--develop-branchs-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
            # -historyVersionJsonF|--history-version-json-file) History_Versions_FILE_PATH=$2; shift 2;;
            -branchT|--branch-logType) branchLogType=$2; shift 2;;  # None \ Notification \ Pgyer
            -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
            --) break ;;
            *) echo $1,$2; break ;;
        esac
    done

    if [ ! -f "${Environment_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您的环境文件${Environment_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi
    
    if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您的环境文件${Environment_FILE_PATH}中未设置分支信息要存放的路径branchsResultJsonFile，请先设置"
        return 1
    fi
    sh ${qbase_update_json_file_singleString_script_path} -jsonF "${Environment_FILE_PATH}" -k "branchsResultJsonFile" -v "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error:设置等下用来保存结果的 branchsResultJsonFile 文件[${RESULT_SALE_TO_JSON_FILE_PATH}]未设置成功，请检查"
        return 1
    fi

    # 是 通知，且允许 markdown 的时候才能真正去尝试markdown
    NotificationMESSAGETYPE=$(cat $Environment_FILE_PATH | jq -r '.package_noti_msgtype')
    if [ "${branchLogType}" == "Notification" ] && [ "${NotificationMESSAGETYPE}" == "markdown" ]; then
        shouldMarkdownOther="true"
    else
        shouldMarkdownOther="false" # 之前未初始化，所以这里得赋值，避免Pgyer用了Notification的值
    fi

    FullChangeLogResult=''
    Escape_FULLTESTINFO_ARRAY_STRING=''
    
    CommitChangeLog=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_update_des') # -r 去除字符串引号
    if [ "${shouldMarkdownOther}" == "true" ]; then
        CommitChangeLog="<font color=warning>${CommitChangeLog}</font>"
    fi
    FullChangeLogResult+="${CommitChangeLog}"
    Escape_FULLTESTINFO_ARRAY_STRING+="\"${CommitChangeLog}\","
    
    if [ "${branchLogType}" == "none" ]; then
        echo "不需要其他打包的分支信息"
        return 0
    fi
    
#    echo "\n\n\n\n\n\n"
    echo "===========================获取当前打包信息(从 ${Environment_FILE_PATH} 的 .developBranchsJsonFile 指向的文件中)==========================="
    shouldMarkdownCurrent=${shouldMarkdownOther}
    Develop_Branchs_FILE_PATH=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.developBranchsJsonFile' | sed 's/\"//g')
    debug_log "正在调用方法(获取当前打包信息,从 ${Develop_Branchs_FILE_PATH} 中):《 getCurrentBranchLog -devBranchsJsonF \"${Develop_Branchs_FILE_PATH}\" -branchLogFor \"${branchLogType}\" -envJsonF \"${Environment_FILE_PATH}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\"》"
    getCurrentBranchLog -devBranchsJsonF "${Develop_Branchs_FILE_PATH}" -branchLogFor "${branchLogType}" -envJsonF "${Environment_FILE_PATH}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error: 在$FUNCNAME里执行 getCurrentBranchLog 失败，请先检查"
        return 1
    fi
    #echo "获取到的当前打包信息=============${currentBranchLogStringResult}"
    if [ -n "${currentBranchLogStringResult}" ] ; then
        if [ "${shouldMarkdownOther}" == "true" ]; then
            FullChangeLogResult+="\n\n\n" # 用企业微信发送 markdown 内容时候，居然三个\n才有空一行纯空的
            Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
            Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
        else
            FullChangeLogResult+="\n\n"
            Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
        fi
        FullChangeLogResult+="${currentBranchLogStringResult}"

        Escape_FULLTESTINFO_ARRAY_STRING+="${Escape_CURRENT_ARRAY_STRING}," # 注意📢:这里不用重复前后多加引号了
    fi
    
    

#    echo "\n\n\n\n\n\n"
    echo "===========================获取上个线上版本分支信息(从 ${Environment_FILE_PATH} 的 .historyVersionJsonFile 指向的文件中)==========================="
    shouldMarkdownLastOnline="false"
    History_Versions_FILE_PATH=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.historyVersionJsonFile' | sed 's/\"//g')
    debug_log "正在调用方法(获取上个线上版本分支信息,从 ${History_Versions_FILE_PATH} 中):《getLastOnlineVersionLog -historyVersionJsonF \"${History_Versions_FILE_PATH}\" -branchLogFor \"${branchLogType}\" -envJsonF \"${Environment_FILE_PATH}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\"》"
    getLastOnlineVersionLog -historyVersionJsonF "${History_Versions_FILE_PATH}" -branchLogFor "${branchLogType}" -envJsonF "${Environment_FILE_PATH}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error: 在 $FUNCNAME 里执行 getLastOnlineVersionLog 失败，请先检查"
        return 1
    fi
    #echo "获取到的上个线上版本分支信息=============${lastOnlineVersionLogStringResult}"
    if [ -n "${lastOnlineVersionLogStringResult}" ] ; then
        # 注意📢：由于 markdown_quote 是使用 echo 来返回值的，所以会丢失其中的换行符，所以我们在修复前，不使用该方法，而直接写源码
        # lastOnlineVersionLogStringResult=$(markdown_quote "${shouldMarkdownOther}" "${lastOnlineVersionLogStringResult}")
       Escape_LASTONLINE_ARRAY_STRING_noQuote=${Escape_LASTONLINE_ARRAY_STRING: 1:${#Escape_LASTONLINE_ARRAY_STRING}-2} # 去除前后的双引号,才能方便修改
       if [ "${shouldMarkdownOther}" == "true" ]; then
            lastOnlineVersionLogStringResult=">${lastOnlineVersionLogStringResult}"
            FullChangeLogResult+="\n\n" # 用企业微信发送 markdown 内容时候，居然三个\n才有空一行纯空的
            # 旧版本使用markdown的引用来更加区分它,且不加尾部不加逗号，因为不用换行
            Escape_FULLTESTINFO_ARRAY_STRING+="\">${Escape_LASTONLINE_ARRAY_STRING_noQuote}\","
        else
            FullChangeLogResult+="\n\n"
            # Escape_FULLTESTINFO_ARRAY_STRING+="\"\","   # 用,来换行
            Escape_FULLTESTINFO_ARRAY_STRING+="\"\n${Escape_LASTONLINE_ARRAY_STRING_noQuote}\","
        fi
        FullChangeLogResult+="${lastOnlineVersionLogStringResult}"
    fi

    
    # 更新
    # FullChangeLogResult="111\n222" # 测试下面更新代码时候使用的简易值
    RESULT_ALL_STRING_SALE_BY_KEY="branch_info_result.${branchLogType}.all.text"
    if [ -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ] && [ -n "${RESULT_ALL_STRING_SALE_BY_KEY}" ]; then
        sh ${CommonFun_HomeDir_Absolute}/update_json_file.sh -f "${RESULT_SALE_TO_JSON_FILE_PATH}" -sk "${RESULT_ALL_STRING_SALE_BY_KEY}" -sv "\"${FullChangeLogResult}\"" --skip-value-check "true"
        if [ $?  != 0 ]; then 
            echo "❌更新最后获得的所有分支信息字符串到文件中，错误啦1。。。。。。"
            exit 1
        fi

        # 去除最后一个字符,即逗号","
        if [ -n "${Escape_FULLTESTINFO_ARRAY_STRING}" ] && [ "${Escape_FULLTESTINFO_ARRAY_STRING}" != "[" ]; then
            Escape_FULLTESTINFO_ARRAY_STRING=${Escape_FULLTESTINFO_ARRAY_STRING: 0:${#Escape_FULLTESTINFO_ARRAY_STRING}-1}
        fi
        all_slice_key="branch_info_result.${branchLogType}.all.slice"
        sh ${CommonFun_HomeDir_Absolute}/update_json_file.sh -f "${RESULT_SALE_TO_JSON_FILE_PATH}" -sk "${all_slice_key}" -sv "[${Escape_FULLTESTINFO_ARRAY_STRING}]" --skip-value-check "true"
        if [ $?  != 0 ]; then 
            echo "$FUNCNAME ❌更新最后获得的所有分支信息字符串到文件中，错误啦3。。。。。。"
            exit 1
        fi
    fi


    # 因为替换的内容比较多，为避免之后使用问题，提前检查替换后是否还是个标准的json文件，防止后续解析失败
    debug_log "正在执行命令(检查分支信息文件的JSON有效性:避免一堆对json的操作后,导致格式不规范,从而影响该文件后续的解析使用)：《 sh ${qbase_json_file_check_script_path} -checkedJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -scriptResultJsonF \"${SCRIPT_RESULT_JSON_FILE}\" 》"
    sh ${qbase_json_file_check_script_path} -checkedJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -scriptResultJsonF "${SCRIPT_RESULT_JSON_FILE}"
    if [ $? != 0 ]; then
        exit_script
    fi
}



REQUEST_FOR_LOG_TYPE_ARRAY=($REQUEST_FOR_LOG_TYPE_ARRAY_STRING)
REQUEST_FOR_LOG_TYPE_COUNT=${#REQUEST_FOR_LOG_TYPE_ARRAY[*]}
echo "要请求的信息类型有${REQUEST_FOR_LOG_TYPE_COUNT}个，分别为REQUEST_FOR_LOG_TYPE_ARRAY=${REQUEST_FOR_LOG_TYPE_ARRAY[*]}"
# 1、先检查文件，避免执行了N个后，才再最后发现有文件缺失，导致整个获取过程以失败告终

# 2、文件检查通过后，正式获取信息
for((i=0;i<${REQUEST_FOR_LOG_TYPE_COUNT};i++));
do
    REQUEST_FOR_LOG_TYPE_STRING=${REQUEST_FOR_LOG_TYPE_ARRAY[i]}
    echo "${YELLOW}正在执行$((i+1))/$((REQUEST_FOR_LOG_TYPE_COUNT))命令以获取分支信息给 ${BLUE}${REQUEST_FOR_LOG_TYPE_STRING}${NC} ${YELLOW}使用：《 ${BLUE}initLastAllChangeLog -envInfoF \"${Environment_FILE_PATH}\" --branch-logType \"${REQUEST_FOR_LOG_TYPE_STRING}\" ${YELLOW}》${NC}"
    initLastAllChangeLog -envInfoF "${Environment_FILE_PATH}" --branch-logType "${REQUEST_FOR_LOG_TYPE_STRING}"
    if [ $? != 0 ]; then
        exit_script
    fi
done
